<template>
  <div class="container">
    <el-row>
      <!-- 左侧面板 -->
      <el-col :span="5">
        <el-card>
          <el-input placeholder="输入关键字进行过滤" v-model="filterText">
          </el-input>
          <!-- 这里可以放置左侧面板的内容 -->
          <el-tree
            :data="sectionTree"
            :current-node-key="currentNodeId"
            node-key="id"
            @node-click="handleNodeClick"
            default-expand-all
            :expand-on-click-node="false"
            :default-checked-keys="defaultcheckedkeys"
          >
            <span class="custom-tree-node" slot-scope="{ node }">
              <span>{{ node.data.name }}</span>
              <span>
                <el-button
                  type="text"
                  size="mini"
                  @click="() => append(node.data)"
                  v-if="
                    !node.data.isSystem || node.data.code === 'CustomCategory'
                  "
                >
                  新增
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="() => edit(node.data)"
                  v-if="
                    !node.data.isSystem && node.data.code !== 'CustomCategory'
                  "
                >
                  编辑
                </el-button>
                <el-button
                  type="text"
                  size="mini"
                  @click="() => remove(node.data.id)"
                  v-if="!node.data.isSystem"
                >
                  删除
                </el-button>
              </span>
            </span>
          </el-tree>
        </el-card>
      </el-col>
      <!-- 右侧列表框 -->
      <el-col :span="18">
        <el-card>
          <div class="handle-box">
            <el-input
              v-model="query.name"
              class="search-input"
              clearable
              placeholder="请输入名称"
            ></el-input>
            <el-button
              type="primary"
              icon="el-icon-search"
              @click="handleSearch"
              >查询</el-button
            >
            <el-button type="primary" icon="el-icon-plus" @click="openNew"
              >新增</el-button
            >
          </div>
          <el-breadcrumb separator="/" class="custom-breadcrumb">
            <el-breadcrumb-item v-for="(item, index) in breadcrumbPath" :key="index">
                {{ item.label }}
            </el-breadcrumb-item>
          </el-breadcrumb>
          <el-table :data="dicItems" border class="table" ref="dicTable">
            <el-table-column
              type="index"
              :min-width="60"
              :width="60"
              label="序号"
            >
              <template slot-scope="scope">{{
                getIndex(scope.$index)
              }}</template>
            </el-table-column>
            <el-table-column prop="name" label="名称"></el-table-column>
            <el-table-column prop="code" label="编码"></el-table-column>
            <el-table-column prop="description" label="描述"></el-table-column>
            <el-table-column label="是否启用">
              <template #default="scope">
                <el-tag :type="scope.row.isEnabled ? 'success' : 'danger'">
                  {{ getDisplayText(scope.row.isEnabled) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column
              label="操作"
              :min-width="500"
              :width="500"
              align="center"
             >
              <template #default="scope"  >
                <el-button text icon="el-icon-edit" @click="editItemDic(scope.row)" :disabled="scope.row.isSystem">
                  编辑
                </el-button>
                <el-button
                  text
                  icon="el-icon-delete"
                  class="red"
                  @click="deleteDicItem(scope.row.id)"
                  :disabled="scope.row.isSystem">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
              background
              layout="total, prev, pager, next"
              :current-page="query.pageIndex"
              :page-size="query.pageSize"
              :total="query.pageTotal"
              @current-change="handlePageChange"
            ></el-pagination>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
        :title="dialogSectionTitle"
        :visible.sync="dialogSectionVisible"
        width="30%"
      >
        <el-form
          ref="sectionform"
          :model="section"
          :rules="sectionRules"
          label-width="120px"
        >
          <el-form-item
            label="上级分类"
            label-width="120px"
            v-if="section.parentId"
          >
            <el-input v-model="section.parentName" disabled></el-input>
          </el-form-item>
          <el-form-item
            label="分类名称"
            required
            prop="name"
            label-width="120px"
          >
            <el-input v-model="section.name" @input="updateCode"></el-input>
          </el-form-item>
          <el-form-item label="分类编码" label-width="120px">
            <el-input v-model="section.code" readonly></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            @click="dialogSectionVisible = false"
            v-if="this.dialogType !== 'view'"
            >取消</el-button
          >
          <el-button
            type="primary"
            @click="saveSection"
            v-if="this.dialogType !== 'view'"
            >确定</el-button
          >
        </div>
      </el-dialog>

      <el-dialog
        :title="dialogDicItemTitle"
        :visible.sync="dialogDicItemVisible"
        width="30%"
      >
        <el-form
          ref="dicItemform"
          :model="dicItem"
          :rules="dicItemRules"
          label-width="120px"
        >
          <el-form-item
            label="所属分类"
            label-width="120px"
            v-if="dicItem.dictionaryId"
          >
            <el-input v-model="dicItem.dictionaryName" disabled></el-input>
          </el-form-item>
          <el-form-item
            label="字典名称"
            required
            prop="name"
            label-width="120px"
          >
            <el-input v-model="dicItem.name" @input="updateDicCode"></el-input>
          </el-form-item>
          <el-form-item label="字典编码" label-width="120px">
            <el-input v-model="dicItem.code" disabled></el-input>
          </el-form-item>
          <el-form-item label="描述" label-width="120px">
            <el-input
              v-model="dicItem.description"
              type="textarea"
              :rows="4"
            ></el-input>
          </el-form-item>
          <el-form-item label="是否启用" label-width="120px">
            <el-switch v-model="dicItem.isEnabled"></el-switch>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogDicItemVisible = false">取消</el-button>
          <el-button type="primary" @click="saveDicItem">确定</el-button>
        </div>
      </el-dialog>
  </div>
</template>
<script>
import {
  getSectionTree,
  CreateDictionaryItemManagement,
  getDicItemByPaged,
  deleteSection,
  deleteDictionaryItem,
  CreateSection,
  updateDictionaryItemManagement,
  updateSection,
} from "@/api/dictionary";
import findNodeById from "@/utils/treeHelper";
import pinyin from "js-pinyin";
let id = 1000;
export default {
  data() {
    return {
      query: {
        name: "",
        code: "",
        treePath: "",
        pageIndex: 1,
        pageSize: 5,
        pageTotal: 0,
      },
      section: {
        parentName: "",
        parentId: "",
        name: "",
        code: "",
        isSystem: false,
      },
      breadcrumbPath:[], // 存储面包屑路径
      filterText: "",
      sectionTree: [],
      currentTreePath: "",
      dicItems: [],
      currentNodeId: "",
      parentSectionName: "",
      dialogType: "",
      defaultcheckedkeys: [],
      dialogSectionVisible: false,
      dialogDicItemVisible: false,
      dialogSectionTitle: "新增分类",
      dialogDicItemTitle: "新增字典项",
      dicItem: {
        dictionaryId: "",
        dictionaryName: "",
        isSystem: false,
        isEnabled: true,
      },
      dicItemRules: {
        name: [
          { required: true, message: "请输入字典名称", trigger: "blur" },
          {
            min: 1,
            max: 15,
            message: "长度在 1 到 15 个字符",
            trigger: "blur",
          },
        ],
      },
      sectionRules: {
        name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          {
            min: 1,
            max: 10,
            message: "长度在 1 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
    };
  },
  mounted() {
    this.loadSetionTree();
  },
  methods: {
    edit(data) {
      var node = findNodeById(this.sectionTree, data.parentId);
      this.section.parentId = node?.id;
      this.section.parentName = node?.name;
      this.section.name = data.name;
      this.section.code = data.code;
      this.section.id = data.id;
      this.section.treePath = data.treePath;
      (this.dialogSectionVisible = true),
        (this.dialogSectionTitle = "编辑分类");
      this.dialogType = "update";
    },
    append(data) {
      var node = findNodeById(this.sectionTree, data.id);
      this.section.parentId = node?.id;
      this.section.parentName = node?.name;
      (this.section.name = ""),
        (this.section.code = ""),
        (this.dialogSectionVisible = true),
        (this.dialogSectionTitle = "新增分类");
      this.dialogType = "add";
    },
    openNew() {
      this.resetDicItem();
      var node = findNodeById(this.sectionTree, this.currentNodeId);
      this.dicItem.dictionaryId = node.id;
      this.dicItem.dictionaryName = node.name;
      this.dialogDicItemVisible = true;
      this.dialogType = "add";
    },
    editItemDic(data){
      var node = findNodeById(this.sectionTree, this.currentNodeId);
      this.dicItem=data;
      this.dicItem.dictionaryId = node.id;
      this.dicItem.dictionaryName = node.name;
      this.dialogDicItemVisible = true;
      this.dialogType="update";
    },
    deleteDicItem(id){
        deleteDictionaryItem(id).then((res) => {
          this.$message({
            message: "删除成功",
            type: "success",
            duration: 1000, // 显示时间为1秒（1000毫秒）
          });
          this.loadDicItem();
        }).catch((error) => this.$message.error(error));
    },
    remove(id) {
      deleteSection(id)
        .then((res) => {
          this.$message({
            message: "删除成功",
            type: "success",
            duration: 1000, // 显示时间为1秒（1000毫秒）
          });
          this.loadSetionTree();
        })
        .catch((error) => this.$message.error(error));
    },

    async handleSearch() {
      await this.loadDicItem();
    },
    updateDicCode() {
      this.dicItem.code = pinyin.getFullChars(this.dicItem.name);
    },
    updateCode() {
      this.section.code = pinyin.getFullChars(this.section.name);
    },
    async handlePageChange(newPage) {
      this.query.pageIndex = newPage;
      await this.loadDicItem();
    },
    getDisplayText(isEnabled) {
      return isEnabled ? "是" : "否";
    },
    saveDicItem() {
      this.$refs["dicItemform"].validate((valid) => {
        if (valid) {
          if (this.dialogType == "add") {
            CreateDictionaryItemManagement(this.dicItem)
              .then((res) => {
                this.$message({
                  message: "新增成功",
                  type: "success",
                  duration: 1000, // 显示时间为1秒（1000毫秒）
                });
                this.dialogDicItemVisible = false;
                this.loadDicItem();
              })
              .catch((error) => {
                this.$message.error(error);
              });
          } else {
            updateDictionaryItemManagement(this.dicItem.id, this.dicItem)
              .then((res) => {
                this.$message({
                  message: "编辑成功",
                  type: "success",
                  duration: 1000, // 显示时间为1秒（1000毫秒）
                });
                this.dialogDicItemVisible = false;
                this.loadDicItem();
              })
              .catch((error) => {
                this.$message.error(error);
              });
          }
        }
      });
    },
    saveSection() {
      this.$refs["sectionform"].validate((valid) => {
        if (valid) {
          if (this.dialogType == "add") {
            CreateSection(this.section)
              .then((res) => {
                this.$message({
                  message: "新增成功",
                  type: "success",
                  duration: 1000, // 显示时间为1秒（1000毫秒）
                });
                this.dialogSectionVisible = false;
                this.loadSetionTree();
              })
              .catch((error) => {
                this.$message.error(error);
              });
          } else {
            updateSection(this.section.id, this.section)
              .then((res) => {
                this.$message({
                  message: "编辑成功",
                  type: "success",
                  duration: 1000, // 显示时间为1秒（1000毫秒）
                });
                this.dialogSectionVisible = false;
                this.loadSetionTree();
              })
              .catch((error) => {
                this.$message.error(error);
              });
          }
        }
      });
    },
    async handleNodeClick(node) {
      this.currentNodeId = node.id;
      this.query.treePath = node.treePath;
      let parts= node.treePath.split("/");
      const filteredParts = parts.filter(item => item !== "");
      this.updateBreadcrumbPath(filteredParts.reverse());
      await this.loadDicItem();

    },
    updateBreadcrumbPath(filteredParts) {
         // 重置面包屑路径
      this.breadcrumbPath = [];
      filteredParts.forEach(item=>{
        var node= findNodeById(this.sectionTree,item);
        if(node){
            this.breadcrumbPath.unshift({ label: node.name });
        }
      });
    },
    getIndex(index) {
      return index + 1;
    },
    resetDicItem() {
        this.dicItem = {
        dictionaryId: "",
        dictionaryName: "",
        isSystem: false,
        isEnabled: true,
        };
    },
    async loadDicItem() {
      var res = await getDicItemByPaged(this.query);
      this.dicItems = res.items;
      this.query.pageTotal = res.totalCount;
    },
    async loadSetionTree() {
      const data = {
        filterText: "",
      };
      this.sectionTree = await getSectionTree(data);
      this.currentNodeId =
        this.sectionTree.length > 0 ? this.sectionTree[0].id : "";
      this.defaultcheckedkeys.push(this.currentNodeId);
      this.query.treePath =
        this.sectionTree.length > 0 ? this.sectionTree[0].treePath : "";
      await this.loadDicItem();
    },
  },
};
</script>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.custom-breadcrumb {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
